package com.example.interceptor;

import com.common.utils.JwtUtil;

import com.common.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class JwtTokenInterceptor implements HandlerInterceptor {


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){

        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        if (request.getRequestURL().toString().contains("login")){
            return true;
        }

        String token = request.getHeader("token");

        if (token == null || token.isEmpty()){
            throw new IllegalArgumentException("token不存在");
        }

        // 解析token
        Claims claims = JwtUtil.parserJwt(token);
        Integer id = claims.get("id", Integer.class); // 显式指定为Integer
        ThreadLocalUtil.set(id.longValue()); // 转换为long
        return true;
    }


    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();//解放ThreadLocal
    }

}
